AI Lessons
Lesson 7: Getting started with p5.js

Purpose: How to draw shapes on a canvas in p5.js, animate them using variables, and display a live webcam feed ready for the AI models used in later lessons.

No. of Classes

1 - (Time : 1 hour 30 minutes, Laptops/desktops : 10, Students strength : 15 to 20).

Materials Required

Computer/Laptop with internet access and the p5.js Web Editor.

Prior knowledge
  • Browsers
  • Basics of HTML
  • Basics of JavaScript - variables and functions
Exercises

Exercise (1)



Exercise (2)



  • Use variables to control the fruit's vertical position and update them inside the draw() function to create continuous up-and-down animation.

Exercise (3)



  • Use createCapture(VIDEO) to display a live webcam feed on the canvas, resize it to match the canvas, and draw a simple shape on top of the video.

Solutions



Teacher's Instruction:
  1. Open the p5.js website and the p5.js Web Editor before the class, and check that the webcam works on the lab machines - Exercise 3 needs it.
  2. Start from the base code linked in Exercise 1 so the students are not typing the p5.js setup from scratch.
  3. Explain that setup() runs once and draw() runs again and again, many times a second. The animation in Exercise 2 comes from changing a variable a little on every pass through draw().
  4. Ask the students how changing a variable affects an object’s position - what happens if the value increases faster, and what happens if it decreases instead.
  5. In Exercise 3 the webcam feed is drawn like any other image, and shapes drawn afterwards appear on top of it. Draw out that the order of the drawing commands decides what covers what.
  6. Points to Ponder:
    • What changes if we stop updating the variable inside draw()?
    • In Exercise 3 the shape stayed on top of the webcam picture. What would happen if you drew the shape first and the video afterwards?